package com.felix.algorithms.planning;

/**
 * BestTimeToBuyAndSellStock
 *
 * @author xuejinhua
 * @date 2018/9/11 17:55
 */
public class BestTimeToBuyAndSellStock {

    public static void main(String[] args) {
        int[] prices = {1,2,3,4,5};
        System.out.println(solution2(prices));
    }

    /**
     * Q121
     *
     * @param prices
     * @return
     */
    public static int solution(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        int max = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] > prices[i]) {
                    int temp = prices[j] - prices[i];
                    max = temp > max ? temp : max;
                }
            }
        }
        return max;
    }

    /**
     * Q122
     *
     * @param prices
     * @return
     */
    public static int solution1(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        int[] values = new int[prices.length - 1];
        for (int i = 0; i < values.length; i++) {
            values[i] = prices[i + 1] - prices[i];
        }
        int sum = 0;
        for (int value : values) {
            if (value > 0) {
                sum += value;
            }
        }
        return sum;
    }

    public static int solution2(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        int[] values = new int[prices.length - 1];
        for (int i = 0; i < values.length; i++) {
            values[i] = prices[i + 1] - prices[i];
        }
        int sum = 0;
        int count = 2;
        while (count > 0) {
            int max = 0;
            int index = -1;
            for (int i = 0; i < values.length; i++) {
                if (values[i] > max) {
                    max = values[i];
                    index = i;
                }
            }
            sum += max;
            if (index != -1){
                values[index] = 0;
            }
            count--;
        }
        return sum;
    }
}
